package com.appbee.news.client.activty;

import java.util.List;

import javax.inject.Inject;

import com.appbee.news.shared.NewsListResultProxy;
import com.appbee.news.shared.NewsProxy;
import com.appbee.news.shared.NewsRequestFactory;
import com.google.gwt.activity.shared.AbstractActivity;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.gwt.user.client.ui.IsWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class RollingNewsActivity extends AbstractActivity
{
	public interface View extends IsWidget
	{

		void showNews(NewsProxy newsProxy);

	}

	private final NewsRequestFactory requestProvider;
	private final View view;
	private List<NewsProxy> newsList;
	private int index = 0;
	private final Scheduler scheduler;
	private boolean running = true;

	@Inject
	public RollingNewsActivity(	View view,
								NewsRequestFactory requestProvider,
								Scheduler scheduler)
	{
		this.view = view;
		this.requestProvider = requestProvider;
		this.scheduler = scheduler;
	}

	@Override
	public void start(AcceptsOneWidget panel, EventBus eventBus)
	{
		requestProvider.getNewsService().findByRange(0, 10)
				.fire(new Receiver<NewsListResultProxy>()
				{
					@Override
					public void onSuccess(NewsListResultProxy response)
					{
						newsList = response.getList();
						schedule();

					}
				});
		panel.setWidget(view);
	}

	@Override
	public void onStop()
	{
		running = false;
		super.onStop();
	}

	private void schedule()
	{
		showNews();
		scheduler.scheduleFixedPeriod(new Scheduler.RepeatingCommand()
		{

			@Override
			public boolean execute()
			{
				showNews();
				return running;
			}
		}, 7 * 1000);

	}

	private void showNews()
	{
		if (index >= newsList.size())
			index = 0;
		NewsProxy newsProxy = newsList.get(index);
		view.showNews(newsProxy);
		index++;
	}

}
